import numpy as np
import cv2 as cv
import sys


def putMultiLineText(
    org_img,
    text,
    org,
    fontFace=cv.FONT_HERSHEY_SIMPLEX,
    fontScale=0.5,
    color=(255, 255, 255),
    thickness=1,
    lineType=cv.LINE_AA,
):
    """
    在图像上绘制多行文本
    """
    img = org_img.copy()
    x, y = org
    lines = []
    # 分割文本为多行
    for line in text.split("\n"):
        lines.append(line)

    # 逐行绘制文本
    for line in lines:
        cv.putText(img, line, (x, y), fontFace, fontScale, color, thickness, lineType)
        # 根据字体大小调整 y 坐标以实现换行
        y += int(fontScale * 30)

    return img


help_str = """
w: blockSize += 2
s: blockSize -= 2
e: C += 1
d: C -= 1

1: THRESH_BINARY
2: THRESH_BINARY_INV

3: ADAPTIVE_THRESH_MEAN_C
4: ADAPTIVE_THRESH_GAUSSIAN_C

q: exit
"""

if __name__ == "__main__":
    file = "../../res/121.jpg"
    if len(sys.argv) > 1:
        file = sys.argv[1]
    img = cv.resize(cv.imread(file), None, fx=0.5, fy=0.5)
    # 1.获取灰度图
    gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    # 2.显示 按键操作说明
    text_gray_img = putMultiLineText(gray_img, help_str, (10, 10), color=(0, 255, 0))
    cv.imshow("text_gray_img", text_gray_img)

    # 3.参数
    maxval = 255
    adaptive_method = cv.ADAPTIVE_THRESH_MEAN_C
    threshold_type = cv.THRESH_BINARY
    blockSize = 11
    C = 2
    while True:
        thresh_img = cv.adaptiveThreshold(
            gray_img, maxval, adaptive_method, threshold_type, blockSize, C
        )
        cv.imshow("thresh_img", thresh_img)
        key = cv.waitKey(0)
        if key == ord("q"):
            break
        elif key == ord("w"):
            blockSize += 2
            blockSize = min(55, blockSize)
        elif key == ord("s"):
            blockSize -= 2
            blockSize = max(3, blockSize)
        elif key == ord("e"):
            C += 1
        elif key == ord("d"):
            C -= 1
        elif key == ord("1"):
            threshold_type = cv.THRESH_BINARY
        elif key == ord("2"):
            threshold_type = cv.THRESH_BINARY_INV
        elif key == ord("3"):
            adaptive_method = cv.ADAPTIVE_THRESH_MEAN_C
        elif key == ord("4"):
            adaptive_method = cv.ADAPTIVE_THRESH_GAUSSIAN_C
        print(f"blockSize:{blockSize}, threshold_type:{threshold_type}, C:{C}, adaptive_method:{adaptive_method}")

    cv.destroyAllWindows()
